package cn.edu.zjut.medlinebackend.job.cycle;

import cn.edu.zjut.medlinebackend.esdao.PictureEsDao;
import cn.edu.zjut.medlinebackend.esdao.PostEsDao;
import cn.edu.zjut.medlinebackend.mapper.PictureMapper;
import cn.edu.zjut.medlinebackend.mapper.PostMapper;
import cn.edu.zjut.medlinebackend.model.Picture;
import cn.edu.zjut.medlinebackend.model.Post;
import cn.edu.zjut.medlinebackend.model.dto.PictureEsDTO;
import cn.edu.zjut.medlinebackend.model.dto.PostEsDTO;
import cn.edu.zjut.medlinebackend.service.PictureService;
import cn.edu.zjut.medlinebackend.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 增量同步图片信息到 es
 *
 */
// todo 取消注释开启任务
@Component
@Slf4j
public class IncSyncPictureToEs {

    @Resource
    private PictureMapper pictureMapper;

    @Resource
    private PictureEsDao pictureEsDao;

    @Resource
    private PictureService pictureService;

    /**
     * 每分钟执行一次
     */
    @Scheduled(fixedRate = 60 * 1000)
    public void run() {
        // 查询近 5 分钟内的数据
        Date fiveMinutesAgoDate = new Date(new Date().getTime() - 5 * 60 * 1000L);
        List<Picture> pictureList = pictureMapper.listPostWithDelete(fiveMinutesAgoDate);
        if (CollectionUtils.isEmpty(pictureList)) {
            log.info("no inc post");
            return;
        }

        List<PictureEsDTO> pictureEsDTOList = new ArrayList<>();
        for(Picture picture: pictureList){
            PictureEsDTO dto = picture.toDTO();
            pictureEsDTOList.add(dto);
        }
        final int pageSize = 500;
        int total = pictureEsDTOList.size();
        log.info("IncSyncPostToEs start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            pictureEsDao.saveAll(pictureEsDTOList.subList(i, end));
        }
        log.info("IncSyncPostToEs end, total {}", total);
    }
}
